package com.example.messangersms;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.example.messangersms.MainActivity;



import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;



public class GetMessageTask extends AsyncTask<Object, Object, ArrayList<Message>>{
    
	static ProgressDialog  mdial = new ProgressDialog(MainActivity.mainContext);
	
	static final String QUERY_STRING="http://softeng.cs.uwosh.edu/students/cs342g5/testxml.php?RecieverId=";
	public static ArrayList<Message> messages;
	public DatabaseConnection dbst;
	protected void onPreExecute()
	{
		mdial.setMessage("Loading Messages..........");
		mdial.show();
	}
	@Override
	protected ArrayList<Message> doInBackground(Object... params) {
		
		XmlPullParser batman = tryDown();
		 try {
			 Log.i("Request failed5", "these is it  in background");
			messages = trygeMessage(batman);
			
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			 Log.i("Request failed5", "these is it  in background");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			 Log.i("Request failed5", "these is it  in background");
		}
		
		return messages;
	}

	private ArrayList<Message> trygeMessage(XmlPullParser batman) throws XmlPullParserException, IOException{
		
        ArrayList<Message> results = new ArrayList<Message>();
		String []  wonderwoman = new String[40];
      
		    int eventType;			 
			eventType = batman.getEventType();
			String currentTag = null;
	        Integer  id = null;
	        String title = null;
	        boolean done = false;
	        String TagTest = null;
	        int i  = 0;
	        while (eventType != XmlPullParser.END_DOCUMENT) {
	        	    
	        	     
	            if(eventType == XmlPullParser.START_DOCUMENT) {
	                 
	                System.out.println("Start document");
	            } else if(eventType == XmlPullParser.END_DOCUMENT) {
	            	
	                System.out.println("End document");
	            } else if(eventType == XmlPullParser.START_TAG) {
	            	TagTest = batman.getName();
	                System.out.println("Start tag "+batman.getName());
	            } else if(eventType == XmlPullParser.END_TAG) {
	            	   TagTest =" ";
	            	 if(batman.getName().equals("Message")){
	                      Message ironMan = new Message(id,title); 
	                     results.add(ironMan);
	            	  }
	                System.out.println("End tag "+batman.getName());
	            } else if(eventType == XmlPullParser.TEXT) {
	            	if (TagTest.equals("SenderId"))
	            	  {
	            		id = Integer.parseInt(batman.getText());
	            	  }
	            	else if (TagTest.equals("Info"))
	            	{
	            		title = batman.getText();
	            	}
	            	   Log.i("Print the variable Tag tyest"," " +TagTest) ;
	            	   Log.i("End tag"," "+batman.getName());
	                   Log.i(" Tag Name" , " "+batman.getText());
	                 
	            }
	             i++;
	            eventType = batman.next();
	           }     
	       
	        
	          
	        return (ArrayList<Message>)results;
	}

	private XmlPullParser tryDown() {
		try{
	       StringBuilder b = new StringBuilder(QUERY_STRING);
	       b.append(LoginActivity.UserId);
	       URI url  = new URI(b.toString());
	       DefaultHttpClient client = new DefaultHttpClient();

	       HttpGet method = new HttpGet(url);

	       HttpResponse res = client.execute(method);

	      
		  XmlPullParser superman = XmlPullParserFactory.newInstance().newPullParser();
		  superman.setInput(new InputStreamReader(res.getEntity().getContent()));
		  Log.i("Request failed3", "ok in first method");
		 

		  return superman;
		}
		catch(XmlPullParserException e)
		{
			 
			Log.i("Request failed1", e.toString());
		}
		catch(IOException e)
		{
			
			Log.i("Request failed2", e.toString());
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			Log.i("Request failed3", e.toString());
			//e.printStackTrace();
			
		}
		
		return null;
		 
	}
   
    @Override
	protected void onPostExecute(ArrayList<Message> result)
	{
		ArrayList<Message> message = result;
		ArrayList<Message> frank =  new ArrayList<Message>();
		dbst = new DatabaseConnection(MainActivity.mainContext);
		int sway = Integer.parseInt(LoginActivity.UserId);
		
		if(dbst.getMessages(sway).size() > 0)
		{
		       frank = dbst.getMessages(sway);
		
	
		       for(Message c: frank)
		       {
		    	   
		    	   message.add(c);
		       }
    }
        
        ArrayAdapter<Message> free = new ArrayAdapter<Message>(MainActivity.mainContext,android.R.layout.simple_list_item_1,message);  
        MainActivity.contactListAdapter=free;
        MainActivity.contactListAdapter.notifyDataSetChanged();  
        MainActivity.listOfContacts.setAdapter(MainActivity.contactListAdapter);
        mdial.dismiss(); 
    
	}
}
